# coding: utf-8
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from common.overwrites import z_render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required

from django.conf import settings
from common.models import User
from common.models.post import Post, PostTag, PostWithTag, Comment
from common.services.user import UserService


@login_required
@csrf_exempt
def create(request):
    if request.method == 'GET':
        tags = PostTag.objects.all()
        return z_render_to_response('create_post.html', {'tags': tags})
    if request.method == 'POST':
        print '-------', request.POST
        tag = PostTag.objects.get(id=int(request.POST.get('tag_id')))
        title = request.POST.get('title')
        content = request.POST.get('content')
        type = request.POST.get('type')

        post = Post.objects.create(user=request.user, title=title, content=content, type=type)
        PostWithTag.objects.create(post=post, tag=tag)
        return HttpResponseRedirect('/post/detail?post_id=%s'%str(post.id))


@csrf_exempt
def post_detail(request):
    post = Post.objects.get(id=int(request.GET.get('post_id')))
    comments = Comment.objects.filter(post=post)
    return z_render_to_response('post_detail.html', {'post': post, 'comments': comments})


@login_required
@csrf_exempt
def comment(request):
    if request.method == 'POST':
        content = request.POST.get('content')
        post_id = request.POST.get('post_id')

        Comment.objects.create(user=request.user, post_id=int(post_id), content=content)
        return HttpResponseRedirect('/post/detail?post_id=%s'%post_id)


@csrf_exempt
def zhan(request):
    if request.method == 'GET':
        if request.session.has_key('_auth_user_id'):
            post = Post.objects.get(id=int(request.GET.get('post_id')))
            post.zhan_count += 1
            post.save()
            return JsonResponse({'result': 'success'})
        else:
            return JsonResponse({'result': 'not_login'})


@csrf_exempt
def post_list(request):
    tag = PostTag.objects.get(id=int(request.GET.get('tag_id')))

    post_ids = PostWithTag.objects.filter(tag=tag).values_list('post', flat=True)
    post_list = Post.objects.filter(id__in=post_ids)
    return z_render_to_response('post_list.html', {'post_list': post_list})